# -*- coding: utf-8 -*-
"""
Created on Sat Jun 14 11:23:16 2014

@author: Adrien
"""

import json


class ModuleException(Exception):
    
    def __init__(self, *args):
        self.args = [a for a in args]
        
    def __str__(self):
        return  " ".join(self.args) 

class ConfigManager:
    def __init__(self,model):
        self.dataModel= model
    
    def save(self,saveFile):
        project ={}
        openedDB={}
        for key, value in self.dataModel.importedDatabaseHandlerPlugins.items():
            options={}
            options["options"]=value.getConfig()
            options["type"]=str(type(value).__name__)
            openedDB[key]=options
        project={'PluginPath':self.dataModel.pluginManager.getPluginPath(),'Databases':openedDB}
        stringToWrite= json.dumps(project,sort_keys=True, indent=4,separators=(',', ': '))
        try:
          myFileobj = open(saveFile,'w')
        except IOError:
             print 'cannot open file'
        myFileobj.write(stringToWrite)
    
    def load(self,openFile):
        try:
          myFileobj = open(openFile,'r')
        except IOError:
             print 'cannot open file'
        json_data=myFileobj.read()
        data = json.loads(json_data)
        self.dataModel.pluginManager.setPluginPath(data['PluginPath'])
        self.dataModel.pluginManager.reloadPlugins()
        self.dataModel.importedDatabaseHandlerPlugins.clear()
        handlers=self.dataModel.pluginManager.getPlugins()
        for key, value in data['Databases'].items():
            try:
                class_ = handlers[value['type']]
            except:
                raise ModuleException(key,"Plugin " + value['type'] + " is not available")
            instance = class_()
            instance.setConfig(value['options'])
            self.dataModel.importedDatabaseHandlerPlugins[class_.__name__]=instance
       
    